//
//  DetailViewController.swift
//  TwERP2017
//
//  Created by Li Xiangyang on 17/5/5.
//  Copyright © 2017年 Li Xiangyang. All rights reserved.
//

import UIKit

class DetailViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,VehSurfaceDataSource{

    @IBOutlet weak var detailDescriptionLabel: UILabel!
    @IBOutlet var gdTitle: UILabel!

    @IBOutlet var cphm: UITextField!
    @IBOutlet var fetchDate: UITextField!
    @IBOutlet var vinCode: UITextField!
    @IBOutlet var wxfl: UITextField!
    @IBOutlet var baoyangDate: UITextField!
    @IBOutlet var custName: UITextField!
    @IBOutlet var servAssistant: UITextField!
    @IBOutlet var miles: UITextField!
    @IBOutlet var phone: UITextField!

    @IBOutlet var serviceItems: UITableView!
    @IBOutlet var partItems: UITableView!
    @IBOutlet var labourSum: UILabel!
    @IBOutlet var partSum: UILabel!
    @IBOutlet var gongdanSum: UILabel!
    
    @IBOutlet var addLabour: UIButton!
    @IBOutlet var addPart: UIButton!
    
    var editingField: UITextField?
    var gongdan: TwERPGongdan?{
        didSet {
            // Update the view.
            DispatchQueue.global(qos: .userInitiated).async {
                self.gongdan?.downloadAttachedFiles()
            }
            configureView()
            
            
        }
    }

    var masterVTC: MasterViewController?
    
    @IBAction func fetchTimeEdit(_ sender: UITextField) {
        let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.locale = Locale(identifier: "zh_CN")
        datePickerView.datePickerMode = UIDatePickerMode.dateAndTime
        sender.inputView = datePickerView
        datePickerView.addTarget(self, action: #selector(DetailViewController.datePickerValueChanged(_:)), for: UIControlEvents.valueChanged)
        editingField = sender
        let dateformatter = DateFormatter()
        dateformatter.dateStyle = DateFormatter.Style.short
        dateformatter.dateFormat = "yyyy-MM-dd hh:mm"
        if let cdate = dateformatter.date(from: sender.text!){
            datePickerView.date = cdate
        }
    }
    
    func datePickerValueChanged (_ sender: UIDatePicker) {
        let dateformatter = DateFormatter()
        dateformatter.dateStyle = DateFormatter.Style.short
        dateformatter.dateFormat = "yyyy-MM-dd hh:mm"
        editingField?.text = dateformatter.string(from: sender.date)
    }
    
    @IBAction func wxflEdit(_ sender: UITextField) {
        let pickerView: UIPickerView = UIPickerView()
        pickerView.dataSource = self
        pickerView.delegate = self
        sender.inputView = pickerView
        if let idx = LoginViewController.gdCategory.index(of: sender.text!)
        {
           // NSLog("idx is: %d", idx)
            pickerView.selectRow(idx, inComponent: 0, animated: true)
        }
    }
    
    @IBAction func saveGongdan(_ sender: Any) {
        self.updateModel()
        
        if !TwERPJsonAgent.isServerReachable() {
            let alert =  UIAlertController(title: "提示", message: "网络连接不正常，请检查！", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
            self.present(alert, animated: true){}
            return
        }
        
        var success = false
        
        if let retStr = self.gongdan?.commit() {
            success = retStr.contains("success")
        }
        
      
        
        
        let hintMessage = success ? "数据保存成功！附件上传中..." : "数据保存不成功！"
    
        
        if(success)
        {
            if(self.gongdan?.operationState == GdInsert)
            {
                gongdan?.refresh()
                self.navigationItem.title = String(format: "工单：%@", (gongdan?.gdNo)!)
                
            }
            self.gongdan?.operationState = GdUploading
            masterVTC?.gdListView.reloadData()
            
            DispatchQueue.global(qos: .userInitiated).async {
                if (self.gongdan?.uploadAttachedFiles())! {
                    self.gongdan?.operationState = GdBrowse
                    DispatchQueue.main.async {
                        self.masterVTC?.gdListView.reloadData()
                    }
                }
            }
            
            
        }
        
        let alert =  UIAlertController(title: "提示", message: hintMessage, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
        self.present(alert, animated: true){}
        

    }
    
    @IBAction func cancelGongdan(_ sender: Any) {
        self.gongdan?.cancelEdit()
        if self.gongdan?.operationState == GdInsert {
            masterVTC?.deleteGongdan(gd: self.gongdan!)
        }
        refreshServiceItems()
        masterVTC?.gdListView.reloadData()
    }
    
    @IBAction func pringGongdan(_ sender: Any) {
        
        TwERPJsonAgent.printGjd((gongdan?.entityId)!)
        let alert =  UIAlertController(title: "提示", message: "已发送打印命令给打印服务器，请检查！", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
        self.present(alert, animated: true){}
        
    }
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        return self.gongdanBeginEdit()
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
       self.updateModel()
        
        

    }
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField.tag == 11 {
        let inverseSet = NSCharacterSet(charactersIn:"0123456789").inverted
        
        // At every character in this "inverseSet" contained in the string,
        // split the string up into components which exclude the characters
        // in this inverse set
        let components = string.components(separatedBy: inverseSet)
        
        // Rejoin these components
        let filtered = components.joined(separator: "")  // use join("", components) if you are using Swift 1.2
        
        // If the original string is equal to the filtered string, i.e. if no
        // inverse characters were present to be eliminated, the input is valid
        // and the statement returns true; else it returns false
            return string == filtered
        } else {
            return true
        }
    }
    
    func updateModel()
    {
        
    self.gongdan?.vehicle.licenseNo = self.cphm.text
        self.gongdan?.vehicle.vinCode = self.vinCode.text
    self.gongdan?.vehicle.customer.shortName = self.custName.text;
    self.gongdan?.vehicle.customer.phone = self.phone.text;
    
    self.gongdan?.category = self.wxfl.text;
    self.gongdan?.serviceAssistant = self.servAssistant.text;
    
        let dateformatter = DateFormatter()
        dateformatter.dateStyle = DateFormatter.Style.short
        dateformatter.dateFormat = "yyyy-MM-dd hh:mm"
        if let cdate = dateformatter.date(from: fetchDate.text!){
            gongdan?.wishFixedTime = cdate
        }
        if let cdate = dateformatter.date(from: baoyangDate.text!){
            gongdan?.nextTime = cdate
        }

        if let ngls = Int(miles.text!) {
            gongdan?.gls = Int32(ngls)
        }
    
    //self.gongdan.problemDescription =self.problemDescription.text;
    //self.gongdan.jywxxm =self.memo.text;
    
    }

    
    //picker view datasource
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return LoginViewController.gdCategory.count
    }
    
    //picker view delegate
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return LoginViewController.gdCategory[row]
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        wxfl.text = LoginViewController.gdCategory[row]
    }
    
    //talbeview datasource delegate
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if self.gongdan == nil { return 0}
        
        if(tableView == self.serviceItems) {
            return self.gongdan!.labourItems.count
        }
        else if(tableView == self.partItems) {
            return self.gongdan!.partItems.count
        }
        return 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       
        let cellIdentifier = tableView == serviceItems ? "Labour Item" : "Part Item"
        let  cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
        
      
        
        if (tableView == self.serviceItems) {
            let labourItem : TwERPLabourItem = gongdan?.labourItems[indexPath.row] as! TwERPLabourItem
            cell.textLabel?.text = labourItem.description
         
            cell.detailTextLabel?.text = String(format: "%d    %1.2f", labourItem.quantity,labourItem.price)
        } else  if (tableView == self.partItems) {
            let partItem : TwERPPartItem = gongdan?.partItems [indexPath.row] as! TwERPPartItem
            cell.textLabel?.text = partItem.partName
            
            cell.detailTextLabel?.text = String(format: "%d    %1.2f", partItem.quantity,partItem.price)
        }
        
        
        return cell

    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let segueIdentifier = tableView == serviceItems ? "Labour Edit" : "Part Edit"
        
        self.performSegue(withIdentifier: segueIdentifier, sender: tableView)
    }
    
     func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    
     func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            if (tableView == self.serviceItems) {
                
            deleteLabourItem(row: indexPath.row)
            } else if tableView == partItems {
                deletePartItem(row: indexPath.row)
            }
            
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
        }
    }

    func refreshServiceItems() {
        if gongdan == nil { return }
        
        labourSum.text = String(format: "%1.2f", (gongdan?.sumOfLabourItems())!)
        partSum.text = String(format: "%1.2f", (gongdan?.sumOfPartItems())!)
        gongdanSum.text = String(format: "%1.2f", (gongdan?.sumOfItems())!)
        serviceItems.reloadData()
        partItems.reloadData()
    }
    
    func deleteLabourItem(row: Int) -> () {
        
        var tempItems = gongdan?.labourItems
        if tempItems != nil{
            tempItems?.remove(at: row)
            gongdan?.labourItems = tempItems
            
        }
        labourSum.text = String(format: "%1.2f", (gongdan?.sumOfLabourItems())!)
        partSum.text = String(format: "%1.2f", (gongdan?.sumOfPartItems())!)
        gongdanSum.text = String(format: "%1.2f", (gongdan?.sumOfItems())!)
        
    }
    
    func deletePartItem(row: Int) -> () {
        
        var tempItems = gongdan?.partItems
        if tempItems != nil{
            tempItems?.remove(at: row)
            gongdan?.partItems = tempItems
            
        }
        labourSum.text = String(format: "%1.2f", (gongdan?.sumOfLabourItems())!)
        partSum.text = String(format: "%1.2f", (gongdan?.sumOfPartItems())!)
        gongdanSum.text = String(format: "%1.2f", (gongdan?.sumOfItems())!)
    }
    
    func configureView() {
        // Update the user interface for the detail item.
           if let gd = gongdan {
            cphm.text = gd.vehicle.licenseNo
            fetchDate.text = gd.date(toString: gd.wishFixedTime)
            vinCode.text = gd.vehicle.vinCode
            wxfl.text = gd.category
            baoyangDate.text = gd.date(toString: gd.nextTime)
            custName.text = gd.vehicle.customer.shortName
            servAssistant.text = gd.serviceAssistant
            miles.text = String(gd.gls)
            
            phone.text = gd.vehicle.customer.phone
            if let mgdNo = gd.gdNo {
                self.navigationItem.title = String(format: "工单：%@", mgdNo)
            }
            
            refreshServiceItems()

        }
       
    }
    override func viewWillDisappear(_ animated: Bool) {
        masterVTC?.view.isUserInteractionEnabled = false
        masterVTC?.navigationItem.leftBarButtonItem?.isEnabled = false
        masterVTC?.navigationItem.rightBarButtonItem?.isEnabled = false
        masterVTC?.navigationItem.titleView?.isUserInteractionEnabled = false
    }
    override func viewDidAppear(_ animated: Bool) {
        masterVTC?.view.isUserInteractionEnabled = true
        masterVTC?.navigationItem.leftBarButtonItem?.isEnabled = true
        masterVTC?.navigationItem.rightBarButtonItem?.isEnabled = true
        masterVTC?.navigationItem.titleView?.isUserInteractionEnabled = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        configureView()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
   
    func checkSurface() {
        performSegue(withIdentifier: "Check Surface", sender: self)
    }
    
    func state(of index: Int32) -> unichar {
        return (self.gongdan?.vehSurface.character(at: Int(index)))!
    }
    
    func setStateOf(_ index: Int32, withValue state: unichar) {
        if !self.gongdanBeginEdit(){
            let alert =  UIAlertController(title: "提示", message: "工单不可修改!", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
            self.present(alert, animated: true){}
   
        } else {
            gongdan?.vehSurface.replaceCharacters(in: NSMakeRange(Int(index), 1), with:  String(UnicodeScalar(state)!))
        }
        
    }
    
    func updateOtherSurfaceView() {
        //
    }
    
    
    func gongdanBeginEdit () -> Bool{
        if self.gongdan == nil {return false}
        
        if self.gongdan!.prepairForEdit()  {
            masterVTC?.gongdanEditStateChange()
            
            return true
        }
        return false
    }
    
    
    override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
        if  identifier == "bcd" || identifier == "abc" {return true}
        if gongdan == nil {
            let alert =  UIAlertController(title: "提示", message: "请先生成工单!", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
            self.present(alert, animated: true){print("hello")}
            return false
        }
        
        if  identifier == "Labour Edit" || identifier == "Part Edit" || identifier == "Load Part" || identifier == "Load Labour"{
            return self.gongdanBeginEdit()
        }
        
        return true
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     
        if (segue.identifier == "Check Surface") {
            let vs = segue.destination as! TwERPVehSurfaceViewController
            vs.surfaceDataSource = self
            return
        }

        if (segue.identifier == "Photos" ){
            let vs = segue.destination as! PhotoCollectionViewController
            vs.gdVTC = self
            return
        }

        if (segue.identifier == "Audios" ){
            let vs = segue.destination as! AudioCollectionViewController
             vs.gdVTC = self
            return
        }

        if (segue.identifier == "Load Labour") {
            let lEditVTC = segue.destination as! FindLabourTableViewController
            lEditVTC.gdVTC = self
            return
        }
        if (segue.identifier == "Load Part") {
            let lEditVTC = segue.destination as! FindPartTableViewController
            lEditVTC.gdVTC = self
            return
        }
        
        if (segue.identifier == "Labour Edit") {
            let lEditVTC = segue.destination as! LabourItemViewController
            lEditVTC.gdVTC = self
            if (sender as? UIButton) != nil {
                
                lEditVTC.item = gongdan?.appendLabourItem()
                
                serviceItems.reloadData()
            } else {
                lEditVTC.item = gongdan?.labourItems[(serviceItems.indexPathForSelectedRow?.row)!] as? TwERPLabourItem
            }
            //lEditVTC.updateView()
            return
        }
        if (segue.identifier == "Part Edit") {
            let lEditVTC = segue.destination as! PartItemViewController
            lEditVTC.gdVTC = self
            if (sender as? UIButton) != nil {
                
                lEditVTC.item = gongdan?.appendPartItem()
                
                partItems.reloadData()
            } else {
                lEditVTC.item = gongdan?.partItems[(partItems.indexPathForSelectedRow?.row)!] as? TwERPPartItem
            }
            //lEditVTC.updateView()
            return
        }

    }
    
  }

